from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError


class ConsignmentReturnWizard(models.TransientModel):
    _name = 'consignment.return.wizard'

    consignment_id = fields.Many2one('consignment.sales',
                                     default=lambda self: self.env.context.get('consignment_id', False))
    product_id = fields.Many2one('product.template', string='Product',
                                 default=lambda self: self.env.context.get('product_id'))
    issued_and_not_used = fields.Float(string='Returnable Qty', compute='_compute_returnable_qty', store=True)
    return_qty = fields.Float(string='Return Qty', default=1)

    def confirmation(self):
        for line in self:
            if line.return_qty > line.issued_and_not_used or line.return_qty <= 0:
                raise ValidationError('Insufficient stock')
            sp_id = self.env['stock.picking'].create({
                'partner_id': line.consignment_id.customer_id.id,
                'picking_type_id': self.env.ref('consignment.cs_stock_pick_type').id,
                'location_id': self.env.ref('consignment.cs_stock_location').id,
                'location_dest_id': self.env.ref('stock.stock_location_stock').id,
                'move_type': 'one',
                'consignment_id': line.consignment_id.id,
                'owner_id': line.consignment_id.customer_id.id,
                'origin': line.consignment_id.name,
                'state': 'done'
            })
            sm = self.env['stock.move'].create({
                'name': line.product_id.name,
                'product_id': line.product_id.product_variant_id.id,
                'product_uom_qty': line.return_qty,
                'quantity': line.return_qty,
                'product_uom': line.product_id.uom_id.id,
                'location_id': sp_id.location_id.id,
                'location_dest_id': sp_id.location_dest_id.id,
                'picking_id': sp_id.id,
                'state': 'done'
            })
            self.env['consignment.sales.line'].create({
                'consignment_id': line.consignment_id.id,
                'product_id': line.product_id.id,
                'quantity': line.return_qty,
                'state': 'refunded',
                'stock_move_id': sm.id,
            })
            return {
                'type': 'ir.actions.act_window',
                'name': 'Stock Picking',
                'res_model': 'stock.picking',
                'view_mode': 'form',
                'res_id': sp_id.id,
                'target': 'current',
                'views': [((False, 'form'))],
                'context': {'default_picking_type_id': self.env.ref('consignment.cs_stock_pick_type').id},
            }

    @api.depends('consignment_id')
    def _compute_returnable_qty(self):
        if not self.consignment_id:
            return 0
        for rec in self:
            rec.issued_and_not_used = rec.consignment_id.qty_shipped - rec.consignment_id.used_qty
            if rec.issued_and_not_used <= 0:
                raise ValidationError(_('There are no returnable quantities'))

    @api.constrains('return_qty')
    def _check_return_qty(self):
        for rec in self:
            if rec.return_qty > rec.issued_and_not_used:
                raise ValidationError(_('Return Qty cannot be greater than Issued and Not Used'))
            elif rec.return_qty <= 0:
                raise ValidationError(_('Return Qty cannot be less than or equal to 0'))
